package com.gln.bloger.action.admin;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;

import com.gln.bloger.constant.Constant;
import com.gln.bloger.pojos.Category;
import com.gln.bloger.pojos.Entry;
import com.gln.bloger.pojos.User;
import com.gln.bloger.pojos.Website;
import com.gln.bloger.util.PagingSupport;
import com.gln.bloger.util.StringUtil;

/**
 * Created on 20080115
 * @author renxj
 * modify entries/articles 
 */
public class EntryAction extends UserBaseAction {
	@SuppressWarnings("unchecked")
	/**
	 * implement dispatchAction's execute method
	 * to put categories into request.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception{
		List<Category> categories = (List<Category>)request.getAttribute("categories");
		   if(null == categories){
			   categories = getCategoryService().getAllCategories(getAuthWebsite(request)).getData();
			   request.setAttribute("categories", categories);
		   }
		return super.execute(mapping, form, request, response);
	}
	/**
	 * add a entry site
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response) 
	       throws Exception{
		ActionMessages errors = form.validate(mapping, request);
		   // get user 
		   User user = getAuthUser(request);
		   // get web site
		   Website website = getAuthWebsite(request);
		   DynaValidatorForm entryForm = (DynaValidatorForm)form;

		   //get form data
		   String id = entryForm.getString("id");
		   String tagStr = entryForm.getString("tags");
		   String cateId = entryForm.getString("category");
		   String content = entryForm.getString("content");
		   String summary = entryForm.getString("summary");
		   String title = entryForm.getString("title");
		   String save = entryForm.getString("save");
		   String publish = entryForm.getString("publish");
		   if(summary == null || summary.trim().length() == 0){
			   summary = StringUtil.truncate(content, 
					                 website.getSummaryLimitLength(), "...");
		   }
		   Entry entry;
		   if(StringUtil.isBlank(id)){
			   entry = new Entry();
		   }else{
			   entry = getEntryService().getEntry(id);
		   }
		   entry.setAuthor(user);
		   entry.setContent(content);
		   if(StringUtil.isBlank(id)){
			   //add entry
			   entry.setDateCreated(new Date());
		   }else{
			   //update entry
			   entry.setId(id);
		   }
		   entry.setDateModified(new Date());
		   entry.setPostIP(request.getRemoteAddr());
		   if(!StringUtil.isBlank(save) && StringUtil.isBlank(publish)){
		       entry.setStatus(Constant.ENTRY_SAVETYPE_SAVE);
		   }else{
			   entry.setStatus(Constant.ENTRY_SAVETYPE_PUBLISH);
		   }
		   entry.setSummary(summary);
		   entry.setTitle(title);
		   entry.setWebsite(website);
		   
		   if(!errors.isEmpty()){
				this.saveErrors(request, errors);
				request.setAttribute("entry", entry);
				return mapping.getInputForward();
			}
		   //pass DTO object to facade, which is transaction manager 
		   getEntryService().saveOrUpdateEntry(entry, cateId, tagStr);
		   /**
		    * remove cached month list and recent entries
		    */
		   getEntryService().clearCachedMonthList();
		   getEntryService().clearCachedRecentEntries();
		   getCategoryService().clearCachedCategories();
		   
		   return mapping.findForward("listEntry");
	}
	
	/**
	 * update entry
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward edit(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response) throws Exception{
		   String entryId = (String)request.getParameter("id");
		   Entry entry = getEntryService().getEntry(entryId);

		   request.setAttribute("entry", entry);
		   return mapping.findForward("entryPage");
	}
	
	/**
	 * delete entry
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward remove(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response) throws Exception{
		   
		   DynaValidatorForm entryForm = (DynaValidatorForm)form;
		   String id = entryForm.getString("id");
		   getEntryService().removeEntry(id);
		   /**
		    * clear cache
		    */
		   getEntryService().clearCachedMonthList();
		   getEntryService().clearCachedRecentEntries();
		   getCategoryService().clearCachedCategories();
		   
		   return mapping.findForward(Constant.SUCCESS);
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward list(ActionMapping mapping, ActionForm form,
			   HttpServletRequest request, HttpServletResponse response) throws Exception{
		Website website = getAuthWebsite(request);	   
		String p = (String)request.getParameter("p");
			   PagingSupport<Entry>
				   entries = getEntryService().
				               getAllEntries(website);

			   if(null != p){
				   entries.setCurrentPage(Integer.parseInt(p));
			   }
			   request.setAttribute("entries", entries);
			   
			   return mapping.findForward("listEntrypage");
	}
	/**
	 * add a entry
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(this.getCategoryService().getAllCategories(getAuthWebsite(request)) == null ){
			ActionMessages errors = new ActionMessages();
			errors.add("errors", new ActionMessage("errors.catefory.needed"));
			return mapping.findForward("adminIndex");
		}
		return mapping.findForward("entryPage");
	}
}
